<template>
	<div v-loading="loading" element-loading-text="加载中">
		<el-form :disabled="compisedit" ref="form" label-position="left" :model="form" label-width="100px"
			style="padding: 20px;">

			<el-form-item label="用户单位">
				<el-select v-model="customerId" placeholder="请选择" filterable :filter-method="customerFilter"
					@change="handleSelectCustomer">
					<el-option v-for="item in customerOptions" :key="item.name" :label="item.name" :value="item._id">
					</el-option>
				</el-select>
			</el-form-item>

			<el-form-item label="联系方式">
				<el-input v-model="form.customer.contact"></el-input>
			</el-form-item>
			<el-form-item label="地址">
				<el-input type="textarea" v-model="form.customer.address"></el-input>
			</el-form-item>


			<el-form-item label="仪器型号">
				<el-input maxlength="10" v-model="form.customer.body_number"></el-input>
			</el-form-item>
			<el-form-item label="序列号">
				<el-input maxlength="10" v-model="form.customer.serial_number"></el-input>
			</el-form-item>

			<el-form-item label="维护">
				<el-input type="textarea" :autosize="{ minRows: 2, maxRows: 20 }" placeholder="请输入内容"
					v-model="form.maintenance">
				</el-input>
			</el-form-item>
			<el-form-item label="维修">
				<el-input type="textarea" :autosize="{ minRows: 2, maxRows: 20 }" placeholder="请输入内容" v-model="form.repair">
				</el-input>
			</el-form-item>
			<el-form-item label="其他">
				<el-input type="textarea" :autosize="{ minRows: 2, maxRows: 20 }" placeholder="请输入内容" v-model="form.other">
				</el-input>
			</el-form-item>

			<el-form-item label="问题点">
				<el-checkbox-group v-model="form.is_daily_equipment">
					<el-checkbox label="设备日常维护" name="type"></el-checkbox>
				</el-checkbox-group>
			</el-form-item>
			<el-input type="textarea" style="margin-bottom: 10pt;" :autosize="{ minRows: 4, maxRows: 20 }"
				placeholder="请输入内容" v-model="form.problem">
			</el-input>

			<el-upload class="upload-demo" :action="uploadBase + 'upload'" :on-preview="handlePreview"
				:on-success="handleProblemSuccess" :on-remove="handleRemove" :file-list="problemFileList"
				list-type="picture">
				<el-button size="small" type="primary">点击上传</el-button>
				<div slot="tip" class="el-upload__tip">可上传文件</div>
			</el-upload>


			<el-row :gutter="24" class="card_block">
				<el-col :span="6" v-for="item in form.problemFileList">
					<!-- 显示图片 -->
					<el-image v-if="item.mimetype.startsWith('image')" size="default"
						:preview-src-list="[uploadBase + item.path]" :preview-teleported=true :src="uploadBase + item.path"
						style="width: 50pt;height: 50pt;" />
					<!-- 显示视频 -->
					<img v-else-if="item.mimetype.startsWith('video')" src="../static/img/video.png"
						style="width: 50pt;height: 50pt;" @click="playVideo(item.path)">
				</el-col>
			</el-row>



			<div v-if="showall">
				<el-form-item label="处理结果">
					<el-checkbox-group v-model="form.solutionCheckList" style="padding: 10pt;">
						<el-checkbox label="校对加样器加样位置"></el-checkbox>
						<el-checkbox label="校对机械手抓卡位置"></el-checkbox>
						<el-checkbox label="检查离心机卡套顺畅度，内部有无杂物"></el-checkbox>
					</el-checkbox-group>
				</el-form-item>
				<el-input style="margin-bottom: 10pt;" type="textarea" :autosize="{ minRows: 4, maxRows: 20 }"
					placeholder="请输入内容" v-model="form.solution">
				</el-input>

				<el-upload class="upload-demo" :action="uploadBase + 'upload'" :on-preview="handlePreview"
					:on-success="handleCompleteSuccess" :on-remove="handleRemove" :file-list="completeFileList"
					list-type="picture">
					<el-button size="small" type="primary">点击上传</el-button>
					<div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
				</el-upload>

				<el-row :gutter="24" class="card_block">
					<el-col :span="6" v-for="item in form.completeFileList">
						<!-- 显示图片 -->
						<el-image v-if="item.mimetype.startsWith('image')" size="default"
							:preview-src-list="[uploadBase + item.path]" :preview-teleported=true
							:src="uploadBase + item.path" style="width: 50pt;height: 50pt;" />
						<!-- 显示视频 -->
						<img v-else-if="item.mimetype.startsWith('video')" src="../static/img/video.png"
							style="width: 50pt;height: 50pt;" @click="playVideo(item.path)">
					</el-col>
				</el-row>



				<el-form-item label="物料表" />
				<el-table :data="form.material_list" show-summary style="width: 100%">

					<el-table-column prop="name" label="物料名称" width="200pt">
						<template slot-scope="scope">
							<el-select v-model="scope.row._id" placeholder="名称" filterable :filter-method="materialFilter"
								@change="materialSelectCompany(scope.$index, scope.row)">
								<el-option v-for="item in materialNameOptions" :key="item._id" :label="item.name"
									:value="item._id">
								</el-option>
							</el-select>
						</template>
					</el-table-column>

					<el-table-column prop="count" label="使用数量">
						<template slot-scope="scope">
							<el-input type="number" v-model="scope.row.count" clearable placeholder="数量">
							</el-input>
						</template>
					</el-table-column>

					<el-table-column prop="amount1" label="单价">
					</el-table-column>

					<el-table-column label="操作" width="80pt">
						<template slot-scope="scope">
							<el-button size="mini" type="danger" @click="handleMaterialDelete(scope.$index, scope.row)">
								删除</el-button>
						</template>
					</el-table-column>

				</el-table>
				<el-button size="mini" type="danger" @click="handleMaterialAdd()">添加</el-button>

				<el-form-item label="差旅费" />
				<el-table :data="form.travel_list" show-summary style="width: 100%">

					<el-table-column prop="name" label="项目" width="auto">
						<template slot-scope="scope">
							<el-input v-model="scope.row.name" placeholder="项目">
							</el-input>
						</template>
					</el-table-column>

					<el-table-column prop="amount1" label="价格" width="100pt">
						<template slot-scope="scope">
							<el-input type="number" v-model="scope.row.amount1" clearable placeholder="价格">
							</el-input>
						</template>
					</el-table-column>

					<el-table-column label="操作" width="80pt">
						<template slot-scope="scope">
							<el-button size="mini" type="danger" @click="handleTravelDelete(scope.$index, scope.row)">删除
							</el-button>
						</template>
					</el-table-column>

				</el-table>
				<el-button size="mini" type="danger" @click="handleTravelAdd()">添加</el-button>

				<el-form-item :label="'总费用:' + totalCost" />

				<el-form-item label="用量表" />
				<el-table :data="form.usage_list" show-summary style="width: 100%">

					<el-table-column prop="name" label="Gle卡名称" width="auto">
						<template slot-scope="scope">
							<el-select v-model="scope.row.name" placeholder="名称">
								<el-option v-for="item in gleNameList" :key="item.name" :label="item.name"
									:value="item.name">
								</el-option>
							</el-select>
						</template>
					</el-table-column>

					<el-table-column prop="count" label="使用数量" width="100pt">
						<template slot-scope="scope">
							<el-input type="number" v-model="scope.row.count" clearable placeholder="数量">
							</el-input>
						</template>
					</el-table-column>

					<el-table-column prop="time" label="时间" width="80pt">
					</el-table-column>

					<el-table-column label="操作" width="80pt">
						<template slot-scope="scope">
							<el-button size="mini" type="danger" @click="handleUsageDelete(scope.$index, scope.row)">删除
							</el-button>
						</template>
					</el-table-column>

				</el-table>
				<el-button size="mini" type="danger" @click="handleUsagelAdd()">添加</el-button>

				<el-form-item label="用户意见" style="margin-top: 10pt;">
					<el-input type="textarea" :autosize="{ minRows: 2, maxRows: 20 }" placeholder="请输入内容"
						v-model="form.user_feedback">
					</el-input>
				</el-form-item>


				<el-row :gutter="24" style="margin-top: 10pt; color: #b3b3b3;">
					<el-col :span="16">
						<h5>工程师签名:</h5>
					</el-col>
					<el-col :span="4" style="text-align: right;">
					</el-col>
					<el-col :span="4" style="text-align: right;">
						<h5>日期:</h5>
					</el-col>
				</el-row>

				<el-row :gutter="24" style="margin-top: 10pt; color: #b3b3b3;">
					<el-col :span="16">
						<h5>客户签名:</h5>
					</el-col>
					<el-col :span="4" style="text-align: right;">
					</el-col>
					<el-col :span="4" style="text-align: right;">
						<h5>日期:</h5>
					</el-col>
				</el-row>
			</div>


			<el-form-item label="团队成员:" v-if="user_list.length != 0">
				<el-row v-for="item in form.member_list">
					<h3>{{ user_list[item._id].name }}</h3>
				</el-row>
			</el-form-item>



		</el-form>
		<div style="position: fixed; bottom: 0; left: 0; right: 0; ">
			<el-button type="danger" style="width: 100vw;" @click="exportWord()">导出</el-button>
		</div>
		<!-- 图片预览对话框 -->

		<el-dialog :fullscreen="true" :visible.sync="previewDialogVisible" style="width: 100vw;height: 100vh;">
			<video :src="previewImageUrl" style="width: 100%;"></video>
		</el-dialog>
	</div>
</template>

<script>
import Api from '../api/api'
export default {
	name: "orderunity",
	data() {
		return {
			loading: true,
			uploadBase: Api.baseUrl,
			customerList: [],
			customerOptions: [],
			materialNameList: [],
			materialNameOptions: [],
			totalCost: 0,
			problemFileList: [],//问题点附件
			completeFileList: [],//完成后附件
			previewDialogVisible: false,
			previewImageUrl: '',
			gleNameList: [],
			user_list: [],
			customerId: 0,
			form: {
				customer: '', //	varchar(255)	用户单位
				assignee: '', //	varchar(50)	指派人
				repairman: '', //	varchar(50)	维修人
				publisher: '',//发布人
				maintenance: '', //	text	维护内容
				repair: '', //	text	维修内容
				other: '', //	text	其他备注
				problem: '', //	text	问题点
				solution: '', //	text	处理结果
				solutionCheckList: [],
				material_list: [],//	text	使用物料清单
				travel_list: [], //	decimal(10,2)	差旅费用
				usage_list: [], //	text	使用量记录
				member_list: [],//成员
				problemFileList: [],//问题点附件
				completeFileList: [],//完成后附件
				user_feedback: '', //	text	用户意见反馈
				priority: '', //	enum('紧急','高','中','低')	处理等级
				status: 0, //	enum(//0待指派 1待接单 2待完成 3已完成 4未完成)	工单状态 
				is_daily_equipment: false, //设备日常维护
			}
		}
	},
	props: {
		showall: {
			type: Boolean,
			default: false
		},
		isedit: {
			type: Boolean,
			default: true
		}

	},
	computed: {
		compisedit() {
			return !this.isedit;
		}
	},
	methods: {
		exportWord() {
			console.log('exportWord')
			Api.genExcel(this.form).then(response => {
				console.log(response.data)
				if (response.status == 200) {
					let url = this.uploadBase + response.data.data.url
					console.log(url)
					window.open(url)
				}
			})
		},
		calculateTotalCost() {
			let cost = 0;
			// 遍历材料列表并将数量乘以单价相加
			for (const material of this.form.material_list) {
				cost += material.count * material.amount1;
			}

			// 遍历差旅费列表并将价格相加
			for (const travel of this.form.travel_list) {
				cost += parseFloat(travel.amount1);
			}
			cost = parseFloat(cost).toFixed(2);
			// 将计算结果分配给 totalCost 属性
			this.totalCost = cost
		},
		customerFilter(val) {
			//this.value = val;
			if (val) {
				const filteredList = [];
				for (var key in this.customerList) {
					let value = this.customerList[key]
					if (value.name.indexOf(val) != -1)
						filteredList.push(value)
				}
				this.customerOptions = filteredList.reduce((obj, item) => {
					obj[item._id] = item;
					return obj;
				}, {});
			}
			else {
				//val为空时，还原数组
				this.customerOptions = this.customerList;
			}
			console.log(this.customerOptions)
		},
		materialFilter(val) {
			//this.value = val;
			if (val) {
				const filteredList = [];
				for (var key in this.materialNameList) {
					let value = this.materialNameList[key]
					if (value.name.indexOf(val) != -1)
						filteredList.push(value)
				}
				this.materialNameOptions = filteredList.reduce((obj, item) => {
					obj[item._id] = item;
					return obj;
				}, {});
			}
			else {
				//val为空时，还原数组
				this.materialNameOptions = this.materialNameList;
			}
			console.log(this.customerOptions)
		},
		materialSelectCompany(index, data) {
			console.log(index, data);
			this.form.material_list[index].amount1 = this.materialNameList[data._id].price;
		},
		handleMaterialAdd() {
			this.form.material_list.push({
				id: '0',
				name: '',
				count: 1,
				amount1: 0,
			})
		},
		handleMaterialDelete(index, data) {
			console.log(index, data);
			this.form.material_list.splice(index, 1)
		},
		handleTravelAdd() {
			this.form.travel_list.push({
				id: '0',
				name: '',
				count: 1,
				amount1: 0,
			})
		},
		handleTravelDelete(index, data) {
			console.log(index, data);
			this.form.travel_list.splice(index, 1)
		},
		handleUsagelAdd() {
			var d = new Date(); //获取系统当前时间
			this.form.usage_list.push({
				id: '0',
				name: '',
				count: 1,
				time: d.toLocaleString(),
			})
		},
		handleUsageDelete(index, data) {
			console.log(index, data);
			this.form.usage_list.splice(index, 1)

		},
		handleRemove(file, fileList) {
			console.log(file, fileList);

		},
		handleProblemSuccess(response, file, fileList) {
			console.log(response.fileinfo)
			this.form.problemFileList.push(response.fileinfo)
			// 处理上传成功后的响应数据
		},
		handleCompleteSuccess(response, file, fileList) {
			// 处理上传成功后的响应数据
			this.form.completeFileList.push(response.fileinfo)
		},
		handlePreview(file) {
			console.log(file);
		},
		onSubmit() {
			console.log('submit!');
		},
		getFormData() {
			return this.form
		},
		setFormData(form) {
			this.form = form
			this.customerId = form.customer._id
			console.log("form", form)
		},
		handleSelectCustomer(value) {
			console.log(this.customerList[value])
			this.form.customer = this.customerList[value]
		},
		// 点击图片时显示全屏图像
		// 点击视频时全屏播放
		playVideo(path) {
			this.previewImageUrl = this.uploadBase + path;
			this.previewDialogVisible = true;
		},
		getUsers() {
			return Api.getUsers({ limit: 1000 }).then(response => {
				console.log(response.data)
				if (response.status == 200) {
					this.user_list = response.data.data.reduce((obj, item) => {
						obj[item._id] = item;
						return obj;
					}, {});
				}
				console.log(response.data)
				return response
			})
		},
		getCustomers() {
			return Api.getCollectWithMd5(Api.md5Customers, Api.getCustomers, 'customers').then(response => {
				if (response.status == 200) {
					this.customerList = response.data.data.reduce((obj, item) => {
						obj[item._id] = item;
						return obj;
					}, {});
					this.customerOptions = this.customerList
				}
				console.log(response.data)
				return response
			})
		},
		getMaterials() {
			return Api.getCollectWithMd5(Api.md5Materials, Api.getMaterials, 'materials').then(response => {
				if (response.status == 200) {
					this.materialNameList = response.data.data.reduce((obj, item) => {
						obj[item._id] = item;
						return obj;
					}, {});
					this.materialNameOptions = this.materialNameList
				}
				console.log(response.data)
				return response
			})
		},
		getGelCards() {
			return Api.getGelCards({ limit: 1000 }).then(response => {
				if (response.status == 200) {
					this.gleNameList = response.data.data.reduce((obj, item) => {
						obj[item._id] = item;
						return obj;
					}, {});
				}
				console.log(response.data)
				return response
			})
		}
	},
	mounted() {
		this.getUsers().then(response => {
			if (response.status == 200) {
				this.getCustomers().then(response => {
					if (response.status == 200) {
						this.getMaterials().then(response => {
							if (response.status == 200) {
								this.getGelCards().then(response => {
									if (response.status == 200) {
										this.loading = false
										this.calculateTotalCost()
									}
								})
							}
						})
					}
				})
			}
		})
	},
	watch: {
		"form.material_list": {
			handler(newVal, oldVal) {
				this.calculateTotalCost()
			},
			deep: true,
			immediate: true
		},
		"form.travel_list": {
			handler(newVal, oldVal) {
				this.calculateTotalCost()
			},
			deep: true,
			immediate: true
		}
	}
}
</script>

<style></style>
